<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\deliver\v1;


use app\api\model\AgencyOrder;
use app\api\model\AgencyTask;
use app\api\model\OrderDeliveryManagerModel;
use redis\RedisPackage;
use shortLink\WxService;
use think\Controller;
use think\Request;
use think\Db;
use app\api\model\Authority;
use think\Exception;

class Agency extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
        
    }
    
    public function getList(AgencyTask $agencyTask,OrderDeliveryManagerModel $deliveryManagerModel)
    {
        $date  = Authority::param(['orderId']);
        $IsStartupDelivere = $deliveryManagerModel->IsStartupDeliverer($date['orderId'], $this->us['user_id'], '');
        if (!empty($IsStartupDelivere)) {
            r_date(null, 300, '请接单后再操作');
        }
        $parem = Request::instance()->post();
        $quer = $agencyTask
            ->with(['CapitalList', 'CapitalList.specsList'])
            ->join('agency', 'agency.agency_id=agency_task.agency_id', 'left')
            ->join('agency_staff', 'agency_staff.id=agency_task.agency_staff_id', 'left')
            ->join('agency_order', 'agency_order.id=agency_task.agency_order_id', 'left')
            ->where(['agency_task.order_id' => $date['orderId']])
            ->where('agency_task.status','<>',2);
        
        $detailed_agency = [];
        if (isset($parem['vendorType']) && $parem['vendorType'] != '') {
            if ($parem['vendorType'] == 1) {
                $detailed_agency = db('detailed_agency')->where('agency_id', $parem['vendorId'])->column('detailed_id');
            } else {
                $quer->where('agency_task.cooperation_type', 1);
            }
        }
        $list      = $quer->where('agency_task.delete_time', 0)
            ->field('agency_task.id,agency_task.order_id,agency_task.agency_staff_id,capital_id,agency_staff.name as agencyStaffName,square,total_cost,agency.agency_name,agency_order.status,agency_task.agency_order_id,agency_order.rejection_user_confirm,agency_order.rejection_reason as reason')
            ->select();
        $listArray = [];
        foreach ($list as $k => $item) {
            foreach ($item['capital_list'] as $value) {
                $group = '';
                if (!empty($item['agency_order_id'])) {
                    $group = $item['agency_order_id'];
                }
                $detailed_option_sku = db('detailed_option_sku')->where('detailed_id',$value['projectId'])->whereIn('option_value_id',array_column($value['specs_list'], 'option_value_id'))->field('id,title')->select();
                if (!empty($detailed_agency) || !empty($agency_task)) {
                    if (in_array($value['projectId'], $detailed_agency) && $item['agency_staff_id']==0) {
                        $listArray[$k]['projectId']       = $value['projectId'];
                        $listArray[$k]['detailed_option_sku']       = empty($detailed_option_sku)?null:$detailed_option_sku;
                        $listArray[$k]['agencyTaskId']    = $item['id'];
                        $listArray[$k]['agencyName']      = $item['agency_name'];
                        $listArray[$k]['agencyStaffName'] = $item['agencyStaffName'];
                        $listArray[$k]['agencyOrderId']   = $item['agency_order_id'];
                        $listArray[$k]['agencyRole']      = empty($item['agency_staff_id']) ? 2 : 1;
                        $listArray[$k]['laborCost']       = $value['labor_cost'];
                        $listArray[$k]['group']           = $group;
                        $listArray[$k]['capital_id']      = $value['capital_id'];
                        $listArray[$k]['smallOrderFee']      = $value['smallOrderFee'];
                        $listArray[$k]['projectTitle']    = $value['projectTitle'];
                        $listArray[$k]['agency_id']       = $value['agency_id'];
                        $listArray[$k]['square']          = $item['square'] . "/" . $value['company'];
                        $listArray[$k]['status']          = empty($item['status']) ? 0 : $item['status'];
                        $listArray[$k]['totalCost']       = $item['total_cost'];
                        $listArray[$k]['TotalQuotation']  = round($value['base_cost'] * $value['square'], 2);
                        $cooperationTypeList              = db('agency', config('database.zong'))->whereIn('agency_id', $value['agency_id'])->select();
                        //1非自营2自营
                        $cooperationType = 1;
                        if (!empty($cooperationTypeList) && in_array("1", array_column($cooperationTypeList, 'cooperation_type'))) {
                            $cooperationType = 2;
                        }
                        $listArray[$k]['cooperationType'] = $cooperationType;
                        $listArray[$k]['specs_list']      = empty($value['specs_list']) ? '' : implode("/", array_column($value['specs_list'], 'option_value_title'));
                        $listArray[$k]['reasonTitle']= '';
                        $listArray[$k]['reason']= '';
                        if(!empty($item['reason']) && $item['status']==2){
                            $listArray[$k]['reasonTitle']= '被供应链驳回，需要你根据驳回原因再次操作';
                            $listArray[$k]['reason']= '不需要用户再次确认，驳回原因：'.$item['reason'];
                            if($item['rejection_user_confirm']==1){
                                $listArray[$k]['reason']= '需要用户再次确认，驳回原因：'.$item['reason'];
                            }
                        }
                    }
                } else {
                    $listArray[$k]['projectId']       = $value['projectId'];
                    $listArray[$k]['detailed_option_sku']       = empty($detailed_option_sku)?null:$detailed_option_sku;
                    $listArray[$k]['agencyTaskId']    = $item['id'];
                    $listArray[$k]['agencyName']      = $item['agency_name'];
                    $listArray[$k]['agencyRole']      = empty($item['agency_staff_id']) ? 2 : 1;
                    $listArray[$k]['agencyStaffName'] = $item['agencyStaffName'];
                    $listArray[$k]['agencyOrderId']   = $item['agency_order_id'];
                    $listArray[$k]['laborCost']       = $value['labor_cost'];
                    $listArray[$k]['group']           = $group;
                    $listArray[$k]['smallOrderFee']      = $value['smallOrderFee'];
                    $listArray[$k]['capital_id']      = $value['capital_id'];
                    $listArray[$k]['projectTitle']    = $value['projectTitle'];
                    $listArray[$k]['square']          = $item['square'] . "/" . $value['company'];
                    $listArray[$k]['status']          = empty($item['status']) ? 0 : $item['status'];
                    $listArray[$k]['totalCost']       = $item['total_cost'];
                    $listArray[$k]['TotalQuotation']  = round($value['base_cost'] * $value['square'], 2);
                    $cooperationTypeList              = db('agency', config('database.zong'))->whereIn('agency_id', $value['agency_id'])->select();
                    //1非自营2自营
                    $cooperationType = 1;
                    if (!empty($cooperationTypeList) && in_array("1", array_column($cooperationTypeList, 'cooperation_type'))) {
                        $cooperationType = 2;
                    }
                    $listArray[$k]['cooperationType'] = $cooperationType;
                    $listArray[$k]['specs_list']      = empty($value['specs_list']) ? '' : implode("/", array_column($value['specs_list'], 'option_value_title'));
                    $listArray[$k]['reasonTitle']= '';
                    $listArray[$k]['reason']= '';
                    if(!empty($item['reason']) && $item['status']==2){
                        $listArray[$k]['reasonTitle']= '被供应链驳回，需要你根据驳回原因再次操作';
                        $listArray[$k]['reason']= '不需要用户再次确认，驳回原因：'.$item['reason'];
                        if($item['rejection_user_confirm']==1){
                            $listArray[$k]['reason']= '需要用户再次确认，驳回原因：'.$item['reason'];
                        }
                    }
                }
                
            }
        }
        $result   = array();
        $tageList = [];
        foreach ($listArray as $k => $v) {
            if (!empty($v['group'])) {
                $result[$v['group']][] = $v;
            } else {
                $result[$k . '/sb'][] = $v;
            }
        }
        foreach ($result as $k => $list) {
            $agencyName = [];
            foreach ($list as $l) {
                if (!empty($l['agencyName']) && empty($l['agencyStaffName'])) {
                    $agencyName[] = $l['agencyName'];
                } elseif (!empty($l['agencyName']) && !empty($l['agencyStaffName'])) {
                    $agencyName[] = $l['agencyName'] . "\n" . $l['agencyStaffName'];
                } elseif (empty($l['agencyName']) && !empty($l['agencyStaffName'])) {
                    $agencyName[] = $l['agencyStaffName'];
                }
                
            }
            $agencyName              = array_unique($agencyName);
            $schemeTag['agencyName'] = '';
            if (!empty($agencyName)) {
                if (count($agencyName) == 1) {
                    $schemeTag['agencyName'] = implode(" ", $agencyName);
                } else {
                    $schemeTag['agencyName'] = implode("\n", $agencyName);
                }
                
            }
            $schemeTag['agencyOrderId']   = $list[0]['agencyOrderId'];
            $schemeTag['cooperationType'] = $result[$k][0]['cooperationType'];
            $schemeTag['status']          = $result[$k][0]['status'];
            $schemeTag['agencyRole']          = $result[$k][0]['agencyRole'];
            $schemeTag['reasonTitle']          = $result[$k][0]['reasonTitle'];
            $schemeTag['reason']          = $result[$k][0]['reason'];
            if ($result[$k][0]['status'] == 0 && !empty($result[$k][0]['agencyStaffName'])) {
                $schemeTag['status'] = 1;
            }
            
            $schemeTag['data'] = $result[$k];
            $tageList[]        = $schemeTag;
        }
        
        r_date($tageList);
    }
    
    public function info(AgencyTask $agencyTask, AgencyOrder $agencyOrder)
    {
        $date            = Authority::param(['agencyOrderId']);
        $agencyOrderList = $agencyOrder->info($date['agencyOrderId']);
        if ($agencyOrderList['code'] == 300) {
            r_date(null, 300, $agencyOrderList['msg']);
        }
        $designer           = $agencyTask->SupplierDetails($date['agencyOrderId']);
        $info['agencyName'] = empty($designer[0]['agency_name']) ? '' : "供应商:\n" . implode("\n", array_unique(array_column($designer, "agency_name")));
        $info['name']       = empty($designer[0]['name']) ? '' : "设计师:\n" . implode("\n", array_unique(array_column($designer, "name")));
        $info['info']       = $agencyOrderList['data'];
        r_date($info);
        
    }
    
    public function add(AgencyTask $agencyTask)
    {
        $date           = Authority::param(['agencyTask', 'agencyId', 'orderId', 'measurementTime', 'solutionCompletionTime', 'generationTime', 'generationCompletionTime', 'installationTime', 'remark', 'submitPicture']);
        $agencyTaskList = json_decode($date['agencyTask'], true);
        $redis    = new RedisPackage();
        $antiDuplication=time();
        $expire=10;
        // 设置缓存 设置缓存过期时间
        $tt=$redis->get(md5($date['agencyId'].$antiDuplication));
        $agencyUserInfo=\db('agency', config('database.zong'))->where('agency_id',  $date['agencyId'])->field('user_id,telephone')->find();
        $agencyUserId=$agencyUserInfo['user_id'];
        $agencyUserPhone=$agencyUserInfo['telephone'];
        if ($tt) {
            r_date(null, 300, "请勿重复提交");
        }
        $redis->set(md5($date['agencyId'].$antiDuplication), md5($date['agencyId'].$antiDuplication),$expire);
        if (empty($date['solutionCompletionTime'])) {
            r_date(null, 300, "请填写方案完成时间");
        }
        if (empty($date['generationCompletionTime'])) {
            r_date(null, 300, "请填写生产完成时间");
        }
        if (empty($date['installationTime'])) {
            r_date(null, 300, "请填写安装完成时间");
        }
        db()->startTrans();
        try {
            $agencyTaskData   = [];
            $OldAgencyOrderId = [];
            $projectId        = [];
            $totalCost        = 0;
            
            foreach ($agencyTaskList as $k => $item) {
                $totalCost                        += $item['totalCost'];
                $agencyTaskData[$k]['id']         = $item['agencyTaskId'];
                $OldAgencyOrderId[]               = $item['agencyOrderId'];
                $agencyTaskData[$k]['total_cost'] = $item['totalCost'];
                $agencyTaskData[$k]['detailedOptionSkuId']=0;
                if(isset($item['detailed_option_sku'])){
                    foreach ($item['detailed_option_sku'] as $k2 => $v2) {
                        if($v2['select']==1){
                            $agencyTaskData[$k]['detailedOptionSkuId'] = $v2['id'];
                        }
                    }
                }
                $projectId[]                      = $item['capital_id'];
                
            }
            $projectTitle=implode(",",array_column($agencyTaskList,'projectTitle'));
            $baseCost = \db('agency_task')->whereIn('capital_id', $projectId)->select();
            $overrun  = $baseCost[0]['overrun'] / 100;
            $baseCost = array_sum(array_column($baseCost, "base_cost"));
//            if ($baseCost + $baseCost * $overrun < $totalCost) {
////                r_date(null, 600, '给供应商的结算价，超出系统设置的成本5%，需要超限审批');
//                throw new Exception('给供应商的结算价，超出系统设置的成本'.($overrun*100).'%，前往企业微信进行超限审批，审批通过后重新提交！！！');
//            }
            if (!empty($OldAgencyOrderId)) {
                \db('agency_order')->whereIn('id', $OldAgencyOrderId)->update(['delete_time' => 0]);
                $status = \db('agency_order')->whereIn('id', $OldAgencyOrderId)->value('status');
                if ($status >= 9) {
                    throw new Exception('供应商已派单确认不可更换供应商！！');
                }
                \db('agency_order_sub')->whereIn('agency_order_id', $OldAgencyOrderId)->update(['delete_time' => time()]);
                \db('agency_order')->whereIn('id', $OldAgencyOrderId)->update(['delete_time' => time()]);
                $agency_task = \db('agency_task')->whereIn('agency_order_id', $OldAgencyOrderId)->find();
                \db('agency_order_modify')->insert(['agency_order_id' => $OldAgencyOrderId, 'type' => 1, 'before_change' => $agency_task['agency_id'], 'after_change' => $date['agencyId'], 'create_time' => time()]);
            }
            $submitPicture = json_decode($date['submitPicture'], true);
            $list          = [
                'order_id' => $date['orderId'],
                'measurement_time' => strtotime($date['measurementTime']),
                'solution_completion_time' => strtotime($date['solutionCompletionTime']),
                'generation_time' => strtotime($date['generationTime']),
                'agency_order_on' => order_sn(),
                'generation_completion_time' => strtotime($date['generationCompletionTime']),
                'installation_time' => strtotime($date['installationTime']),
                'remark' => $date['remark'],
                'disclose' => empty($submitPicture) ? '' : $date['submitPicture'],
                'create_time'=>time(),
                'status' => 5
            ];
            
            $agencyOrderId  = \db('agency_order')->insertGetId($list);
            $agencyOrderSub = \db('agency_order_sub')->insertGetId(['order_id' => $date['orderId'], 'agency_order_id' => $agencyOrderId, 'status' => 1, 'agency_id' => $date['agencyId'],'create_time'=>time()]);
            $list=null;
            foreach ($agencyTaskData as $k => $item) {
                \db('agency_task')->where('id', $item['id'])->update(['agency_order_id' => $agencyOrderId, 'agency_order_sub_id' => $agencyOrderSub, 'total_cost' => $item['total_cost'], 'agency_id' => $date['agencyId'], 'update_time' => time(),'detailed_option_sku_id'=>$item['detailedOptionSkuId']]);
                $list[]=['id'=>floatval($item['id']),'total_cost'=> $item['total_cost']];
                
            }
            
            $phone= \db('agency_user', config('database.zong'))->where('agency_id',  $date['agencyId'])->value('phone');
            db()->commit();
            if($agencyUserId ==0){
                sendMsg($phone,462761105);
            }
            if($agencyUserId !=0){
                //供应链经理确认
                $managerMessage=manager(floatval($agencyOrderSub),floatval($agencyOrderId),'',$list);
                $managerMessage=json_decode($managerMessage,true);
                if($managerMessage['code']==0){
                    \db('agency_order')->where('id', $agencyOrderId)->update(['store_confirm_time' => time(), 'status' => 3,'rejection_reason'=>'','rejection_user_confirm'=>0]);
                    //用户确认
                    $UserConfirmMessage=UserConfirm($agencyOrderId);
                    $UserConfirmMessage=json_decode($UserConfirmMessage,true);
                    if($UserConfirmMessage['errcode'] !=200){
                        r_date(null, 300, $UserConfirmMessage['msg']);
                    }
                    sendMsg($agencyUserPhone,475011024,[$this->us['username'],$projectTitle,$baseCost]);
                }else{
                    r_date(null, 300, $managerMessage['msg']);
                }
            }
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 设计师表
     */
    public function agencyUserList()
    {
        $appUser = db('agency_staff', config('database.zong'))
            ->where('agency_staff.status', 1)
            ->where('agency_staff.delete_time', 0)
            ->field('agency_staff.id,agency_staff.mobile,agency_staff.name')
            ->order('id desc')
            ->select();
        
        r_date($appUser, 200);
    }
    
    /*
   * 设计师提交
   */
    public function agencyUserListAdd()
    {
        $date           = Authority::param(['agencyTask', 'designerId']);
        $agencyTaskList = json_decode($date['agencyTask'], true);
        if (empty($date['designerId'])) {
            r_date(null, 300, '设计师不能为空');
        }
        if (empty($agencyTaskList)) {
            r_date(null, 300, '清单不能为空');
        }
        $id          = array_column($agencyTaskList, 'agencyTaskId');
        $agency_task = \db('agency_task')->join('capital', 'capital.capital_id=agency_task.capital_id', 'left')->whereIn('agency_task.id', $id)->select();
        $mobile = \db('agency_staff', config('database.zong'))->where('id', $date['designerId'])->value('mobile');
        foreach ($agency_task as $item) {
            if (!empty($item['agency_id'])) {
                r_date(null, 300, $item['class_b'] . "已指派供应商无法添加设计师");
            }
        }
        
        \db('agency_task')->whereIn('id', $id)->update(['agency_staff_id' => $date['designerId'],'update_time'=>time()]);
        sendMsg($mobile, 462736135,[$this->us['username']]);
        sleep(1);
        r_date(null, 200);
    }
    
    public function SupplierConfirmation(AgencyTask $agencyTask)
    {
        $date         = Authority::param(['agencyOrderId']);
        $list         = $agencyTask
            ->with(['CapitalList', 'CapitalList.specsList'])
            ->join('agency_order', 'agency_order.id=agency_task.agency_order_id', 'left')
            ->join('agency_order_sub', 'agency_order_sub.agency_order_id=agency_task.agency_order_id', 'left')
            ->where(['agency_task.agency_order_id' => $date['agencyOrderId']])
            ->field('agency_task.id,agency_task.agency_staff_id,agency_task.user_input_cost,agency_task.order_id,capital_id,square,total_cost,agency_task.agency_order_id,agency_order.attachment,agency_order_sub.attachment as attachments')
            ->where('agency_task.delete_time', 0)
            ->group('agency_task.capital_id')
            ->select();
        $listIntArray = [];
        $listArray    = [];
        foreach ($list as $k => $item) {
            foreach ($item['capital_list'] as $value) {
                
                $listArray[$k]['projectTitle'] = $value['projectTitle'];
                $listArray[$k]['square']       = $item['square'] . "/" . $value['company'];
                $listArray[$k]['priceChanges']       = "";
                if(bcsub($item['user_input_cost'],$item['total_cost'],2) !=0 && $item['agency_staff_id']==0){
                    $listArray[$k]['priceChanges']       = "注意:供应商修改成本:由".$item['user_input_cost']."元修改为".$item['total_cost']."元";
                }
                
                $listArray[$k]['totalCost']    = $item['total_cost'];
                $listArray[$k]['laborCost']    = $value['labor_cost'];
                $listArray[$k]['specsList']    = empty($value['specs_list']) ? '' : implode("/", array_column($value['specs_list'], 'option_value_title'));
                $attachment=!empty(json_decode($list[0]['attachment'], true))?json_decode($list[0]['attachment'], true):[];
                $attachments=!empty(json_decode($list[0]['attachments'], true))?json_decode($list[0]['attachments'], true):[];
                $listArray[$k]['img']          = array_merge($attachment,$attachments);
                $listArray[$k]['specsList']    = empty($value['specs_list']) ? '' : implode("/", array_column($value['specs_list'], 'option_value_title'));
                
                
                $listIntArray[$k]['projectTitle'] = $value['projectTitle'];
                $listIntArray[$k]['square']       = $item['square'] . "/" . $value['company'];
                $listIntArray[$k]['toPrice']      = $value['toPrice'];
                $listIntArray[$k]['specsList']    = empty($value['specs_list']) ? '' : implode("/", array_column($value['specs_list'], 'option_value_title'));
            }
        }
        $attachment=!empty($list['attachment'])?json_decode($list[0]['attachment'], true):[];
        $attachments=!empty($list['attachments'])?json_decode($list[0]['attachments'], true):[];
        $attachment=!empty($attachment)?$attachment:[];
        $attachments=!empty($attachments)?$attachments:[];
       
        $img         = array_merge($attachment,$attachments);
        r_date(['quoteList' => $listIntArray, 'measureList' => $listArray, 'img' => $img, 'agencyOrderId' => $date['agencyOrderId']], 200);
    }
    
    /*
     * 供应链设确认提交
     */
    public function SupplierConfirmationSubject(AgencyTask $agencyTask)
    {
        $date = Authority::param(['agencyOrderId']);
        $total_cost=\db('agency_task')->where('agency_order_id', $date['agencyOrderId'])->select();
        $totalSumMoney=array_sum(array_column($total_cost,'total_cost'));
        if($totalSumMoney==0){
            r_date(null, 300,'成本为0，无法通过，请联系供应商，把成本修改为和单据一致的金额');
        }
        $agency_order= \db('agency_order')->where('id', $date['agencyOrderId'])->find();
        
        if($agency_order['rejection_user_confirm']==1 || $agency_order['rejection_user_confirm']==0){
            \db('agency_order')->where('id', $date['agencyOrderId'])->update(['store_confirm_time' => time(), 'status' => 3,'rejection_reason'=>'','rejection_user_confirm'=>0]);
        }
        
        //1非自营2自营
        $cooperationType = 1;
        if ($total_cost[0]['agency_staff_id'] !=0) {
            $cooperationType = 2;
        }
        if($agency_order['rejection_user_confirm']==2){
            $status=7;
            if($cooperationType==2){
                $status=4;
            }
            \db('agency_order')->where('id', $date['agencyOrderId'])->update(['status' => $status,'store_confirm_time' => time(),'rejection_reason'=>'','rejection_user_confirm'=>0]);
        }
        
        sleep(1);
        r_date(null, 200);
    }
    
    /*
     * 异常原因
     */
    public function abnormalCause()
    {
        $abnormal_cause      = \db('sys_config', config('database.zong'))->where('statusss', 1)->where('keyss', 'abnormal_cause')->value('valuess');
        $abnormal_settlement = \db('sys_config', config('database.zong'))->where('statusss', 1)->where('keyss', 'abnormal_settlement')->value('valuess');
        r_date(['abnormalCause' => json_decode($abnormal_cause, true), 'abnormalSettlement' => json_decode($abnormal_settlement, true)], 200);
    }
    
    /*
    * 异常原因提交
    */
    public function abnormalCauseSubject()
    {
        $date                 = Authority::param(['agencyOrderId', 'attachment', 'abnormalCause', 'abnormalCauseReason']);
        $abnormalCause        = json_decode($date['abnormalCause'], true);
        $attachment        = json_decode($date['attachment'], true);
        $abnormalCauseContent = [];
        foreach ($abnormalCause as $item) {
            if ($item['select'] == 1) {
                $abnormalCauseContent[] = $item;
            }
        }
        if (empty($abnormalCauseContent)) {
            r_date(null, 300, "请选择异常原因");
        }
        \db('agency_abnormal')->insert([
            'agency_order_id' => $date['agencyOrderId'],
            'attachment' => empty($attachment) ? '' : $date['attachment'],
            'abnormal_cause' => implode(',', array_column($abnormalCauseContent, 'id')),
            'create_time' => time(),
            'abnormal_cause_reason' => implode(',', array_column($abnormalCauseContent, 'title')) . "-" . $date['abnormalCauseReason'],
        ]);
        sleep(1);
        r_date(null, 200);
    }
    
    /*
     * 清单时候关联供应商
     */
    public function agencyAssociation()
    {
         //2是设计师1是供应商
         $date = Authority::param(['orderId', 'id', 'vendorType', 'agencyOrderId']);
         $agency=db('agency',config('database.zong'))->where('agency_id', $date['id'])->find();
         if ($date['vendorType'] == 2) {
             $capital = \db('agency_task')->where('agency_task.status','<>',2)->where('agency_task.agency_staff_id', 0)->where('agency_task.agency_id', 0)->whereIn('cooperation_type', 1)->where('order_id', $date['orderId'])->count();
         } else {
             $detailed_agency = db('detailed_agency')->where('agency_id', $date['id'])->column('detailed_id');
             $capital         = \db('capital')->join('agency_task', 'agency_task.capital_id=capital.capital_id', 'left')->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->where(function ($quer) use ($date) {
                 $quer->where('agency_task.agency_id', 0)->whereOr('agency_task.agency_order_id', $date['agencyOrderId']);
             })->where('ordesr_id', $date['orderId'])->where('agency_task.status','<>',2)->whereIn('capital.projectId', $detailed_agency);
 
             $capital=$capital->where('capital.enable', 1)->where('capital.types', 1)->where('capital.agency', 1)->count();
         }
         
         $capitalCount = 0;
         if ($capital != 1) {
             $capitalCount = 1;
         }
         if($agency['user_id'] !=0){
             $capitalCount = 0;
         }
         r_date($capitalCount, 200);
    }
    
    public function WxService(){
        $date = Authority::param(['agencyOrderId']);
        $post_data = [
            'path' => 'pages/order/materialConfirmationLetter/materialConfirmationLetter',
            'query' => "id={$date['agencyOrderId']}",
            'env_version' => 'release',
            'expire_type' => 1,
            'expire_interval' => 179
        ];
        $WxService = new WxService();
        $url       = $WxService->getWxUrlLink($post_data);
        r_date('https://yiniao.co/wx.html?'.explode('?',$url)[1], 200);
        
    }
    
}